/**
 * 
 */
package com.xbang.attendance.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.xbang.attendance.entity.product.Product;
import com.xbang.attendance.entity.product.ProductCategory;
import com.xbang.attendance.service.ProductCategoryService;
import com.xbang.attendance.service.ProductService;
import com.xbang.core.utils.ReflectionUtils;

import enumeration.MeasureUnit;
import enumeration.ProductStatus;

/**
 * @author dev.zhang
 * 
 */
// @Service("productAnalyzeService")
public class ProductAnalyzeServiceImpl extends AbstractAnalyzeService {

	// @Autowired
	private ProductCategoryService productCategoryService;
	// @Autowired
	private ProductService productService;

	private Map<String, String> fieldMapping = new HashMap<String, String>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.xbang.attendance.service.AnalyzeService#analyse(java.io.File)
	 */
	public void analyse(File file) throws Exception {
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;
		fs = new POIFSFileSystem(new FileInputStream(file));
		wb = new HSSFWorkbook(fs);
		HSSFSheet sheet = wb.getSheetAt(0);
		setupExcelFieldMappings(sheet);
		int categoryColumnIndex = getCategoryIndex();
		int measureUnitColumnIndx = getMeasureUnitExcelIndex();
		for (Row row : sheet) {
			if (row.getRowNum() == 0) {
				continue;
			}

			if (getCellValue(row.getCell(0)) == null || getCellValue(row.getCell(0)).toString().trim().isEmpty()) {
				continue;
			}

			Object categoryCode = null;
			if (measureUnitColumnIndx != -1) {
				categoryCode = getCellValue(row.getCell(categoryColumnIndex));
			}
			categoryCode = categoryCode == null ? "other" : ReflectionUtils.parseString(categoryCode);
			ProductCategory category = null;
			if (categoryCode != null) {
				category = productCategoryService.getCategoryByCode(categoryCode.toString());

				if (category == null) {
					throw new Exception("产品类别" + getCellValue(row.getCell(0)).toString() + "不存在!");
				}
			}
			Product product = new Product();
			String measureUnit = "";
			if (measureUnitColumnIndx != -1) {
				measureUnit = ReflectionUtils.parseString(getCellValue(row.getCell(measureUnitColumnIndx)));
			}
			if (product.isTrueMeasureUnit(measureUnit)) {
				product.setMeasureUnit(MeasureUnit.valueOf(measureUnit));
			} else {
				product.setMeasureUnit(MeasureUnit.Barrel);
			}

			for (Iterator<Map.Entry<String, Integer>> excelFieldMappingIterator = excelFieldMapping.entrySet().iterator(); excelFieldMappingIterator.hasNext();) {
				Entry<String, Integer> excelFieldMappingEntry = excelFieldMappingIterator.next();
				Cell tmpCell = row.getCell(excelFieldMappingEntry.getValue());
				if (tmpCell != null && tmpCell.getColumnIndex() != categoryColumnIndex && tmpCell.getColumnIndex() != measureUnitColumnIndx) {
					Object object = getCellValue(tmpCell);
					if (object != null && fieldMapping.containsKey(excelFieldMappingEntry.getKey())) {
						String propertyName = fieldMapping.get(excelFieldMappingEntry.getKey()).split(":")[0];
						ReflectionUtils.setFeildByApacheCheckString(product, propertyName, object);
					}
				}
			}

			product.setProductCategory(category);
			product.setProductStatus(ProductStatus.confirm);
			if (productService.checkProduct(product.getProductCode())) {
				Product tmpProduct = productService.getProductByCode(product.getProductCode());
				tmpProduct = tmpProduct.copyPropereties(product);
				productService.update(tmpProduct);

				continue;
			}
			productService.save(product);
		}
	}

	private int getMeasureUnitExcelIndex() {

		if (excelFieldMapping.containsKey("计量单位")) {
			return excelFieldMapping.get("计量单位");
		} else
			return -1;
	}

	private int getCategoryIndex() {
		if (excelFieldMapping.containsKey("产品类别编码")) {
			return excelFieldMapping.get("产品类别编码");
		} else
			return -1;
	}

	/**
	 * @param productCategoryService
	 *            the productCategoryService to set
	 */
	public void setProductCategoryService(ProductCategoryService productCategoryService) {
		this.productCategoryService = productCategoryService;
	}

	/**
	 * @param productService
	 *            the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * @param fieldMapping
	 *            the fieldMapping to set
	 */
	public void setFieldMapping(Map<String, String> fieldMapping) {
		this.fieldMapping = fieldMapping;
	}

}
